#include "mainwindow.h"
#include "ui_mainwindow.h"
#include <QSerialPortInfo>
#include <QTime>
#include <QSerialPort>
#include <QDebug>
#include <QMessageBox>
#include <QHostInfo>

QSerialPort* my_serialPort;

/*
 * 名称:get_localmachine_name
 * 功能:获取本机机器名称
 * 参数:no
 * 返回:QString
 */
QString get_localmachine_name()
{
    QString machineName     = QHostInfo::localHostName();
    return machineName;
}


MainWindow::MainWindow(QWidget *parent) :
    QMainWindow(parent),
    ui(new Ui::MainWindow)
{
    ui->setupUi(this);

    //button
    ui->pushButton->setGeometry(QRect(140,100,100,40));

    //串口初始化
    my_serialPort = new QSerialPort(this);

    if(QHostInfo::localHostName()=="DESKTOP-NKOIGCI")
    {
        my_serialPort->setPortName("COM4");
    }
    else
    {
        qDebug() << QHostInfo::localHostName();
        my_serialPort->setPortName("ttyUSB0");
    }
    my_serialPort->setBaudRate(9600);//波特率
    my_serialPort->setDataBits(QSerialPort::Data8);//数据字节，8字节
    my_serialPort->setParity(QSerialPort::NoParity);//校验，无
    my_serialPort->setFlowControl(QSerialPort::NoFlowControl);//数据流控制,无
    my_serialPort->setStopBits(QSerialPort::OneStop);//一位停止位
    //my_serialPort->open(QIODevice::ReadWrite);
    //connect(mySerialPort,SIGNAL(readyRead()),this,SLOT(serialReadData()));

    if (my_serialPort->open(QIODevice::ReadWrite)) {
        qDebug() << "Opened port";
    } else {
        qDebug() << "Port error on open:" << my_serialPort->errorString();
    }

}


MainWindow::~MainWindow()
{
    delete ui;
}

void MainWindow::on_pushButton_clicked()
{
    if(my_serialPort->isOpen())
    {
        my_serialPort->write("fffff");
    }
    else
    {
        QMessageBox::warning(this,tr("错误"),tr("串口被占用！"),QMessageBox::Ok);
    }
//
//    char test[5] = {0x01,0x02,0x03,0x04,0x05};

//    my_serialPort->write(test);//发送
}

